import { request } from '@/api/request';
import { Chartdata, CourseDataVO, CourseType, getCourseList, postPlanDataList } from '@/api/StatisticsApi';
import IconFont from '@/components/IconFont';
import { useAppSelector } from '@/redux/store';
import { useRequest, useSize } from 'ahooks';
import { Empty } from 'antd';
import * as echarts from 'echarts';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import StudyStatisticsSelect, { StudyStatisticsSelectProps } from './components/StudyStatisticsSelect';
import OStyle from './index.less';
import { NoListDom } from './NoListDom';
import PlanLearnTable from './PlanLearnTable';

let myChart: echarts.ECharts;

export default function LearningStatisticsPage() {
  const navigator = useNavigate();
  // organizationType - 1: 协会, 0: 企业
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt);
  const chartDom = useRef<HTMLDivElement>(null);
  const size = useSize(chartDom.current);
  const [activePlanId, setActivePlanId] = useState<string>();
  const [planLearnType, setPlanLearnType] = useState('1');

  const [courseDataList, setCourseDataList] = useState<CourseDataVO[]>([]);
  const [selectedOutlineEnterprise, setSelectedOutlineEnterprise] = useState<string>(entId);
  const [selectedstudySituationEnterprise, setSelectedstudySituationEnterprise] = useState<string>(entId);

  useRequest(
    () => {
      if (organizationType === 1) {
        return getCourseList(entId);
      } else {
        return postPlanDataList({
          pageNum: 1,
          pageSize: 99999,
          curEntId: entId,
          entId: selectedOutlineEnterprise,
        });
      }
    },
    {
      onSuccess(data) {
        if (data && data.length) {
          setCourseDataList(data);
          setActivePlanId(data[0].courseGuid);
        } else {
          setCourseDataList([]);
          setActivePlanId(undefined);
        }
      },
      refreshDeps: [selectedOutlineEnterprise],
    },
  );

  const [chartdata, setChartdata] = useState<Chartdata[]>([]);

  useEffect(() => {
    let url, tempParams;

    if (!activePlanId || !chartDom.current) return;

    myChart = chartDom.current && echarts.init(chartDom.current);
    myChart.showLoading({
      text: '加载中...',
      color: '#F66E2C',
    });

    if (organizationType === 1) {
      url = '/safe/api/statistics/getCycleStudyList';

      tempParams = {
        entId,
      };
    } else {
      url = '/safe/api/statistics/getEntCycleStudyList';

      tempParams = {
        curEntId: entId,
        entId: selectedOutlineEnterprise,
      };
    }
    request<Chartdata[]>({
      url: url,
      params: {
        pageNum: 1,
        pageSize: 9999,
        courseGuid: activePlanId,
        ...tempParams,
      },
      noAutoShowErrorMessage: true,
    }).then((data) => {
      const chartDataList = data.data;

      setChartdata([...chartDataList]);

      const xAxisData: string[] = []; //横坐标
      const noStudyPersonNum: number[] = []; //未学
      const studyPersonNum: number[] = []; //已学

      chartDataList.forEach((e) => {
        const xm = e.startDate + ' — ' + e.endDate;

        xAxisData.push(xm);
        noStudyPersonNum.push(e.noStudyPersonNum);
        studyPersonNum.push(e.studyPersonNum);
      });
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function (params: { marker: string; axisValue: string; dataIndex: number }[]) {
            let tipTxt = '<div>';

            tipTxt += `${params[0].axisValue}<br />`;
            tipTxt += `${params[0].marker} 已学人数: ${studyPersonNum[params[0].dataIndex]}<br />`;
            tipTxt += `${params[1].marker} 未学人数: ${noStudyPersonNum[params[1].dataIndex]}`;
            tipTxt += '</div>';

            return tipTxt;
          },
        },
        legend: {
          selectedMode: false,
          right: '24px',
          top: '24px',
          data: ['已学', '未学'],
        },
        color: ['#3BD59A', '#FF4A4A'],
        xAxis: {
          data: xAxisData,
          axisLabel: {
            rotate: 30,
          },
          axisLine: {
            lineStyle: {
              color: '#999',
              width: 1,
            },
          },
        },
        yAxis: {
          axisLine: {
            lineStyle: {
              color: '#999',
              width: 1,
            },
          },
        },
        grid: {
          left: '80px',
          right: '80px',
          top: 70,
          bottom: 75,
        },
        series: [
          {
            name: '已学',
            type: 'line',
            smooth: false,
            data: studyPersonNum,
          },
          {
            name: '未学',
            type: 'line',
            smooth: false,
            data: noStudyPersonNum,
          },
        ],
      };

      myChart.setOption(option);
      myChart.hideLoading();

      const resize = () => {
        if (myChart) {
          myChart.resize();
        }
      };

      window.addEventListener('resize', resize);

      return () => {
        if (myChart) {
          echarts.dispose(myChart);
        }

        window.removeEventListener('resize', resize);
      };
    });
  }, [activePlanId, size, chartDom.current, selectedOutlineEnterprise]);

  const onOutlineSelect: StudyStatisticsSelectProps['onChange'] = (value) => {
    setSelectedOutlineEnterprise(value);
  };

  const onStudySituationSelect: StudyStatisticsSelectProps['onChange'] = (value) => {
    setSelectedstudySituationEnterprise(value);
  };

  const navigateToHistory = () => {
    navigator('/statistics/history');
  };

  return (
    <>
      <div style={{ overflowY: 'auto', height: '100%' }}>
        <div className={OStyle.topMian}>
          <div className={OStyle.headT}>
            <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
              <div className={OStyle.head_tit}>概要</div>
              {organizationType === 0 && (
                <StudyStatisticsSelect value={selectedOutlineEnterprise} onChange={onOutlineSelect} />
              )}
            </div>
          </div>
          <div className={OStyle.topContent}>
            <div style={{ borderRight: '1px solid #f2f2f2' }}>
              <div className={OStyle.cycle_study_list}>
                {courseDataList.length > 0 ? (
                  courseDataList.map((item: CourseType, index) => {
                    return (
                      <div
                        className={`${activePlanId == item.courseGuid ? OStyle.cycle_study_li_active : undefined} ${
                          OStyle.cycle_study_li
                        }`}
                        key={index}
                        onClick={() => {
                          setActivePlanId(item.courseGuid);
                        }}
                      >
                        <div className={OStyle.cycle_study_li_name} title={item.name}>
                          {item.name}
                        </div>
                      </div>
                    );
                  })
                ) : (
                  <NoListDom />
                )}
              </div>
            </div>

            <div id="Chart" ref={chartDom} style={{ flexGrow: 1, height: '411px' }}></div>

            {!chartdata.length || !activePlanId ? (
              <div className={OStyle.nochartdata}>
                <Empty />
              </div>
            ) : null}
          </div>
        </div>

        <div className={OStyle.topMian}>
          <div className={OStyle.headT} style={{ border: 'none' }}>
            <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
              <div className={OStyle.head_tit}>计划学习情况</div>
              {organizationType === 0 && (
                <StudyStatisticsSelect value={selectedstudySituationEnterprise} onChange={onStudySituationSelect} />
              )}
            </div>
            <div style={{ color: '#999999', cursor: 'pointer' }} onClick={navigateToHistory}>
              查看历史
              <IconFont type="icon-xiangyou" style={{ marginLeft: '2px', fontSize: 14, color: '#999999' }} />
            </div>
          </div>
          <PlanLearnTable type={planLearnType} enterpriseId={selectedstudySituationEnterprise} />
        </div>
      </div>
    </>
  );
}
